/* 
购物的控制层
*/
const { dbsql } = require('../model/model')

// 加入购物车
exports.doAddCart = (req, res) => {
  let { b_id, num } = req.body
  
  // 检查用户是否登录
  if (!req.data || !req.data.u_id) {
    return res.send({ code: 401, message: '请先登录', data: null });
  }
  
  let u_id = req.data.u_id
  // 首先判断当前登录用户购物车是否存在该商品
  let sql = `SELECT * FROM shopcart WHERE u_id=? AND b_id=?;`
  dbsql(sql, [u_id, b_id], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '出现错误' + err.message, data: null })
    }
    if (results.length > 0) {
      // 该用户购物车已经有该商品，只修改数量（在用来的基础上+num）
      let sql2 = `UPDATE shopcart SET num=num+? WHERE cart_id=?;`
      dbsql(sql2, [Number(num), results[0].cart_id], (err2, results2) => {
        console.log(err2);
        
        if (err2) {
          return res.send({ code: 101, message: '购物车数量更新出现错误' + err2.message, data: null })
        }
        console.log(231);
        
        return res.send({ code: 200, message: '商品已经成功添加到购物车', data: results2 })
      })
    } else {
      // 该用户购物车没有该商品，新增一条数据
      let sql3 = `INSERT INTO shopcart(u_id, b_id, num) VALUES(?,?,?);`
      dbsql(sql3, [u_id, b_id, num], (err3, results3) => {
        if (err3) {
          return res.send({ code: 101, message: '购物车数量更新出现错误' + err3.message, data: null })
        }
        return res.send({ code: 200, message: '商品已经成功加入购物车', data: results3 })
      })
    }
  })
}

// 展示购物车
exports.showCart = (req, res) => {
  // 如果用户未登录，返回空数组
  if (!req.data || !req.data.u_id) {
    return res.send({ code: 200, message: null, data: [] });
  }
  
  let u_id = req.data.u_id;
  let sql = `SELECT * FROM shopcart JOIN book ON shopcart.b_id=book.b_id WHERE u_id=?;`
  dbsql(sql, [u_id], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '出现错误' + err.message, data: null })
    }
    res.send({ code: 200, message: null, data: results })
  })
}

// 修改购物车数量
exports.doUpdateCartNum = (req, res) => {
  let { id, num } = req.body
  let sql = `UPDATE shopcart SET num=? WHERE cart_id=?;`
  dbsql(sql, [num, id], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '出现错误' + err.message, data: null })
    }
    res.send({ code: 200, message: null, data: results })
  })
}

// 删除购物车数据
exports.doDelCart = (req, res) => {
  let { id } = req.query  //传参方式? 用query
  let sql = `DELETE FROM shopcart WHERE cart_id=?;`
  dbsql(sql, [id], (err, results) => {
    if (err) {
      return res.send({ code: 101, message: '出现错误' + err.message, data: null })
    }
    res.send({ code: 200, message: null, data: results })
  })
}